<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择类型" clearable>
          <el-option label="请选择字典生成" value="" />
        </el-select>
      </el-form-item>
      <el-form-item label="品牌信息" prop="brand">
        <el-select v-model="queryParams.brand" placeholder="请选择品牌信息" clearable>
          <el-option v-for="productBrand in productBrandList"
                      :value="productBrand.id"
                      :key="productBrand.id"
                     :label="productBrand.name"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="商品状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择商品状态" clearable>
          <el-option
            v-for="dict in dict.type.sys_normal_disable"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['product:info:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['product:info:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['product:info:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['product:info:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="infoList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编号" align="center" prop="id">
        <template slot-scope="scope">
          {{scope.$index +1}}
        </template>
      </el-table-column>
      <el-table-column label="名称" align="center" prop="name" />
      <el-table-column label="单位" align="center" prop="unit" />
      <el-table-column label="类型" align="center" prop="typeName" />
      <el-table-column label="主图" align="center" prop="img" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.img" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="轮播图" align="center" prop="carouselImages" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.carouselImages" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="评论数" align="center" prop="commentCount" />
      <el-table-column label="收藏人气" align="center" prop="collectCount" />
      <el-table-column label="品牌信息" align="center" prop="brandName" />
      <el-table-column label="商品状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['product:info:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['product:info:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改商品信息对话框 -->
    <!--    TODO 回来 -->
    <el-dialog :title="title" :visible.sync="open" width="80%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-steps :active="productEditStatus" simple>
          <el-step title="基础信息" icon="el-icon-edit"></el-step>
          <el-step title="规格信息" icon="el-icon-shopping-cart-full"></el-step>
          <el-step title="描述信息" icon="el-icon-notebook-2"></el-step>
        </el-steps>
        <div style="width: 100%; margin-top: 25px;">
        <el-row v-show="productEditStatus == 1" :gutter="15">
        <el-col :span="12">
          <el-form-item label="名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入名称" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="搜索关键字" prop="keywords">
            <el-input v-model="form.keywords"  placeholder="请输入内容" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="单位" prop="unit">
            <el-input v-model="form.unit" placeholder="请输入单位" />
          </el-form-item>
        </el-col>
          <el-col :span="12">
            <el-form-item label="商品状态">
              <el-radio-group v-model="form.status">
                <el-radio
                  v-for="dict in dict.type.sys_normal_disable"
                  :key="dict.value"
                  :label="dict.value"
                >{{dict.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        <el-col :span="12">
          <el-form-item label="类型" prop="type">
            <!--          <el-select v-model="form.type" placeholder="请选择类型">-->
            <!--            <el-option label="请选择字典生成" value="" />-->
            <!--          </el-select>-->
            <el-cascader
              v-model="productTypeArr"
              :props="{label:'name',value:'id'}"
              :options="treeTypeList"
              @change="productTypeChange"></el-cascader>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="品牌信息" prop="brand">
            <el-select style="width: 100%" v-model="form.brand" clearable placeholder="请选择品牌信息">
              <el-option v-for="productBrand in productBrandList"
                         :value="productBrand.id"
                         :key="productBrand.id"
                         :label="productBrand.name"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item label="主图">
            <image-upload v-model="form.img"/>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="轮播图">
            <image-upload v-model="form.carouselImages"/>
          </el-form-item>
        </el-col>
      </el-row>
        <el-row v-show="productEditStatus == 2" :gutter="15">
          <el-col :span="24">
            <el-form-item label="规格信息" prop="ruleAttrId">
              <el-select @change="changeRule" style="width: 100%" v-model="form.ruleAttrId" placeholder="请选择规格信息">
                <el-option v-for="rule in ruleList" :label="rule.name" :value="rule.id" :key="rule.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col v-show="form.ruleAttrId !=''" :span="24">
            <el-form :inline="true" :model="ruleTableBody" class="demo-form-inline">
              <el-form-item label="编号">
                <el-input style="width: 120px;" v-model="ruleTableBody.number" placeholder="编号"></el-input>
              </el-form-item>
              <el-form-item label="进价">
                <el-input-number
                  style="width: 120px;"
                  v-model="ruleTableBody.purchasePrice"
                  controls-position="right"
                  :min="0"
                  :max="9999999"
                  :precision="2"
                ></el-input-number>
              </el-form-item>
              <el-form-item label="价格">
                <el-input-number
                  style="width: 120px;"
                  v-model="ruleTableBody.price"
                  controls-position="right"
                  :min="0"
                  :max="9999999"
                  :precision="2"
                ></el-input-number>
              </el-form-item>
              <el-form-item label="售价">
                <el-input-number
                  style="width: 120px;"
                  v-model="ruleTableBody.sellingPrice"
                  controls-position="right"
                  :min="0"
                  :max="9999999"
                  :precision="2"
                ></el-input-number>
              </el-form-item>
              <el-form-item label="库存">
                <el-input-number
                  style="width: 120px;"
                  v-model="ruleTableBody.stock"
                  controls-position="right"
                  :min="0"
                  :max="9999999"
                  :precision="2"
                ></el-input-number>
              </el-form-item>
              <el-form-item label="重量">
                <el-input-number
                  style="width: 120px;"
                  v-model="ruleTableBody.weight"
                  controls-position="right"
                  :min="0"
                  :max="9999999"
                  :precision="2"
                ></el-input-number>
              </el-form-item>
              <el-form-item label="体积">
                <el-input-number
                  style="width: 120px;"
                  v-model="ruleTableBody.volume"
                  controls-position="right"
                  :min="0"
                  :max="9999999"
                  :precision="2"
                ></el-input-number>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="oneClickSettings">一键设置</el-button>
              </el-form-item>
            </el-form>
          </el-col>
          <el-col v-show="form.ruleAttrId != ''" :span="24">
            <el-table :data="ruleTableBodyList" height="500">
              <el-table-column v-for="ruleTableTitle in ruleTableTitleList"
              :label="ruleTableTitle.label" :prop="ruleTableTitle.prop"
               :width="ruleTableTitle.prop == 'image'? '200px': '0'"
              >
                <template slot-scope="scope">
                  <span v-if="ruleTableBodyInput.indexOf(ruleTableTitle.prop) == -1 && ruleTableTitle.prop != 'image'">{{scope.row[ruleTableTitle.prop]}}</span>
                  <el-input v-if="ruleTableBodyInput.indexOf(ruleTableTitle.prop) > -1 && ruleTableTitle.prop != 'image'" v-model="scope.row[ruleTableTitle.prop]"></el-input>
                  <image-upload :is-show-tip="false" :limit="1" v-if="ruleTableTitle.prop == 'image'"  v-model="scope.row[ruleTableTitle.prop]"/>
                </template>
              </el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-link type="primary" @click="deleteRuleTableBodyRow(scope.$index)">移除</el-link>
                </template>
              </el-table-column>
            </el-table>
          </el-col>
        </el-row>
        <el-row v-show="productEditStatus == 3" :gutter="15">
          <el-col :span="12">
            <el-form-item label="描述">
              <editor v-model="form.productDesc"  :min-height="192"/>
            </el-form-item>
          </el-col>
        </el-row>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-show="productEditStatus != 1" type="primary" @click="up">上一步</el-button>
        <el-button v-show="productEditStatus != 3" type="primary" @click="next">下一步</el-button>
        <el-button v-show="productEditStatus == 3" type="primary" @click="submitForm">提交</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listInfo, getInfo, delInfo, addInfo, updateInfo } from "@/api/product/info";
import { treeType } from "../../../api/product/type";
import { findAll } from "../../../api/product/brand";
import {ruleFindAll} from "../../../api/product/rule";

export default {
  name: "Info",
  dicts: ['sys_normal_disable'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商品信息表格数据
      infoList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        keywords: null,
        type: null,
        brand: null,
        status: null,
      },
      // 表单参数
      form: {},
      productTypeArr:[],
      // 表单校验
      rules: {
        name: [
          { required: true, message: "名称不能为空", trigger: "blur" }
        ],
        keywords: [
          { required: true, message: "搜索关键字不能为空", trigger: "blur" }
        ],
        productDesc: [
          { required: true, message: "描述不能为空", trigger: "blur" }
        ],
        unit: [
          { required: true, message: "单位不能为空", trigger: "blur" }
        ],
        type: [
          { required: true, message: "类型不能为空", trigger: "change" }
        ],
        img: [
          { required: true, message: "主图不能为空", trigger: "blur" }
        ],
        carouselImages: [
          { required: true, message: "轮播图不能为空", trigger: "blur" }
        ],
        brand: [
          { required: true, message: "品牌信息不能为空", trigger: "change" }
        ],
        status: [
          { required: true, message: "商品状态不能为空", trigger: "blur" }
        ],
        ruleAttrId: [
          { required: true, message: "规格信息不能为空", trigger: "change" }
        ],
        createBy: [
          { required: true, message: "创建人不能为空", trigger: "blur" }
        ],
        createTime: [
          { required: true, message: "创建时间不能为空", trigger: "blur" }
        ],
      },
      //类型的树型对象
      treeTypeList: [],
      //商品品牌列表
      productBrandList:[],
      //商品维护状态
      productEditStatus:1,
      ruleList:[],
      ruleTableTitleListTemplate:[
        {label: "编号",prop:"number"},
        {label: "进价",prop:"purchasePrice"},
        {label: "价格",prop:"price"},
        {label: "售价",prop:"sellingPrice"},
        {label: "库存",prop:"stock"},
        {label: "图片",prop:"image"},
        {label: "重量",prop:"weight"},
        {label: "体积",prop:"volume"},
      ],
      ruleTableTitleList: [],
      ruleTableBodyList:[],
      ruleTableBodyInput:["number","purchasePrice","price","sellingPrice","stock","weight","volume"],
      ruleTableBodyTemplate:{
        stock:'',
        price:'',
        purchasePrice:'',
        sellingPrice:'',
        image:'',
        number:'',
        weight:'',
        volume:''
      },
      ruleTableBody:{
        stock:'',
        price:'',
        purchasePrice:'',
        sellingPrice:'',
        image:'',
        number:'',
        weight:'',
        volume:''
      }

    };
  },
  created() {
    this.getList();
    this.treeTypeInit();
    this.productBrandLists();
    this.ruleListInit();
  },
  methods: {
    /** 查询商品信息列表 */
    getList() {
      this.loading = true;
      listInfo(this.queryParams).then(response => {
        this.infoList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        keywords: null,
        productDesc: null,
        unit: null,
        type: null,
        img: null,
        carouselImages: null,
        commentCount: null,
        collectCount: null,
        brand: null,
        status: "0",
        ruleAttrId: null,
        revision: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.resetForm("form");
      this.productTypeArr = [],
        this.ruleTableBody={
          number:'',
          stock:'',
          price:'',
          purchasePrice:'',
          sellingPrice:'',
          weight:'',
          volume:''
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加商品信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getInfo(id).then(response => {
        this.form = response.data;
        this.productTypeArr =  this.form.typeArr.split(",")
        this.productEditStatus = 1;
        //规格获取
        let productRuleCenterList = this.form.productRuleCenterList;
        //还原之前的prop结构 sku -> prop
        productRuleCenterList.forEach((productRule)=>{
          let props = productRule.sku.split(",");
          props.forEach((prop,index)=>{
            productRule["prop"+index] = prop;
          })
        })
        //规格赋值
        this.ruleTableBodyList = productRuleCenterList;
        //表头
        this.ruleTableTitleList = []
        //先找到规格内容
        this.ruleList.forEach((rule,index)=>{
          if(rule.id == this.form.ruleAttrId){
          const {ruleAttr} = rule;
          let ruAttrJson = JSON.parse(ruleAttr);
          ruAttrJson.forEach((attr,index)=>{
              this.ruleTableTitleList.push(0,{label:attr.key,prop:"prop"+index})
          })
          }
        })
        this.ruleTableTitleListTemplate.forEach((ruleTableTitle) => this.ruleTableTitleList.push(ruleTableTitle))
        this.open = true;
        this.title = "修改商品信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.ruleTableBodyList.forEach((ruleTableBody) => {
            let sku = [];
            for (let ruleTableBodyKey in ruleTableBody){
              if (ruleTableBodyKey.indexOf("prop") > -1){
                sku.push(ruleTableBody[ruleTableBodyKey])
              console.log(ruleTableBodyKey);
              }
            }
            ruleTableBody['sku'] = sku.toString();
          })
          this.form.productRuleCenterList= this.ruleTableBodyList;
          if (this.form.id != null) {
            updateInfo(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addInfo(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除商品信息编号为"' + ids + '"的数据项？').then(function() {
        return delInfo(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('product/info/export', {
        ...this.queryParams
      }, `info_${new Date().getTime()}.xlsx`)
    },
    /**
     * 初始化联机选择器
     */
    treeTypeInit(){
      treeType().then(response => {
        this.treeTypeList = response.data
      })
    },
    //缓存选择器选中事件
    productTypeChange(values){
      console.log(values)
    this.form.typeArr = values.toString();
    this.form.type = values[values.length - 1]
    },
    //商品品牌列表
    productBrandLists(){
      findAll().then(response =>{
        console.log(response.data)
        this.productBrandList = response.data;
      })
    },
    //控制商品添加节奏
    up(){
      if(this.productEditStatus > 1){
        --this.productEditStatus;
      }
    },
    next(){
      if(this.productEditStatus == 1){
      if(!this.baseCheck()){
        return;
      }
      }
      if(this.productEditStatus < 3){
        ++this.productEditStatus;
      }
    },
    //基础信息 校验
    baseCheck(){
      let baseCheckStatus = true;
      this.$refs["form"].validateField(["name","keywords","unit","type","brand","status"],valid => {
        if(valid!= null && valid != ''){
          baseCheckStatus =  false;
        }
      })
      return baseCheckStatus;
    },
    ruleListInit(){
      ruleFindAll().then(response =>{
        // 从响应结果集当中 取出 规格的集合
        let rules = response.data;
        //对规格集合进行循环
        rules.forEach((rule)=>{
          //获取规格当中的规格详情
          const {ruleAttr} =rule;
          //把规详情转化为JSON类型
          let ruleAttrObj = JSON.parse(ruleAttr);
          //定义一个规格详情名称的数组
          let ruleAttrAttr =[];
          //循环把规格详情的名称添加到数据当中
            ruleAttrObj.forEach(({key}) => {
              ruleAttrAttr.push(key);
          })
          //把规格的名称 重新进行 重写
          rule.name = rule.name+ "- ("+ruleAttrAttr.toString()+")"
        })
        this.ruleList = rules;
      })
    },
    //规格选择触发事件
    changeRule() {
      //表单选中后的id
      let ruleAttrId = this.form.ruleAttrId;
      //定义规格信息的载体
      let ruleInfo = null;
      //通过选择的规格id获取 规格的信息
      this.ruleList.forEach((rule) => {
        if (ruleAttrId ==rule.id){
          ruleInfo = rule;
        }
      })
      const {ruleAttr} = ruleInfo;
      //转化成JSON字符串
      let ruleAttrJson = JSON.parse(ruleAttr);
      //表单的表头
      let ruleTitle = [];
      //表单的表头前缀
      let prop = 'prop';
      let propArr = [];
      // let ruleTableBody ={... this.ruleTableBodyTemplate}
      // let valueProp = [];
      //表单body 的属性值
      let valuesArr = [];
      ruleAttrJson.forEach(({key,values},index) => {
        // let ruleTableBody ={... this.ruleTableBodyTemplate}
        ruleTitle.push({"label":key,"prop":prop+index})
        // ruleTableBody[prop+index] = prop + index;
        // this.ruleTableBodyList.push(ruleTableBody)
        // valueProp.push(value+index)
        valuesArr.push(values);
      })
      //表body的对象
      let ruleAttrBodyList = [];
      //多少条记录
      let ruleAttrBodyListSize = 1;
      valuesArr.forEach((values) => {
        ruleAttrBodyListSize = ruleAttrBodyListSize*values.length
      })
      for (let i = 0; i < ruleAttrBodyListSize; i++) {
        let ruleAttrBody = {... this.ruleTableBodyTemplate};
        propArr.forEach((prop) => {
          ruleAttrBody[prop] = '';
        })
        ruleAttrBodyList.push(ruleAttrBody);
      }

      valuesArr.forEach((values , valuesIndex) => {
        //位置
        let prop = "prop"+valuesIndex;
        //出现次数
        let showNum = 1;
        for (let i = 0; i < valuesIndex; i++) {
          showNum = showNum*valuesArr[i].length;
        }
        //循环次数
        let forNum = 1;
        for (let i = valuesIndex +1 ; i < valuesArr.length; i++) {
          forNum = forNum*valuesArr[i].length;
        }
        //计数器
        let valueIndex = 0;
        for (let i = 0; i <forNum ; i++) {
          values.forEach((value) => {
            for (let j = 0; j < showNum; j++) {
              ruleAttrBodyList[valueIndex][prop] = value
              valueIndex++
            }
          })
        }
      })
      this.ruleTableBodyList = ruleAttrBodyList
      this.ruleTableTitleListTemplate.forEach((ruleTableTitle) => {
        ruleTitle.push(ruleTableTitle);
        // ruleTableBody[] = ''
      })
      this.ruleTableTitleList = ruleTitle;
    },
    //移除
    deleteRuleTableBodyRow(rowIndex){
      this.ruleTableBodyList.splice(rowIndex,1)
    },
    //TODO 底部
    oneClickSettings(){
      let number = 1;
      for (let ruleTableBodyKey in this.ruleTableBody){
        this.ruleTableBodyList.forEach((ruleBody) =>{
          if(ruleTableBodyKey == "number"){
            ruleBody[ruleTableBodyKey] = this.ruleTableBody[ruleTableBodyKey] +(number++);
          }else {

            ruleBody[ruleTableBodyKey] = this.ruleTableBody[ruleTableBodyKey];
          }
        })
      }
    }
  }
};
</script>
